package com.huaxin.hxcloud.activity;

import android.app.ProgressDialog;
import android.content.Context;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.huaxin.common.Entity.HxCommitTaskDetailBean;
import com.huaxin.common.Entity.HxFacilityTaskDetailBean;
import com.huaxin.common.tools.HxTransmitRequestHelper;
import com.huaxin.common.tools.RequestHelper;
import com.huaxin.common.utils.DialogUtil;
import com.huaxin.common.utils.ToastUtil;
import com.huaxin.common.utils.Util;
import com.huaxin.hxcloud.R;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by songxf on 2017/9/6. 设备巡检项
 */

class HxDeviceJunJianTaskDetailAdater extends BaseQuickAdapter<HxFacilityTaskDetailBean.DataBean.DeviceJaListBean.DeviceItemBean, HxDeviceJunJianTaskDetailAdater.ViewHolder> {

    private static int STATE_NORMAL  = 1;//正常
    private static int STATE_ERROR   = 2;//异常
    private static int COMMIT_FINSIH = 1;//提交完成
    private List<HxFacilityTaskDetailBean.DataBean.DeviceJaListBean.DeviceItemBean> mDeviceItem;
    private Context                                                                 mContext;
    private HxTaskDetailImageAdapter                                                mImageAdapter;
    private HxFacilityTaskDetailActivity                                            mActivity;
    private HxSationDialogFragment mDialogFrament;
    private HxFacilityTaskDetailBean.DataBean.DeviceJaListBean.DeviceItemBean       mDeviceItemBean;
    private int                                                                     mIsFinish;
    public HxDeviceJunJianTaskDetailAdater(Context context, int isFinish, List<HxFacilityTaskDetailBean.DataBean.DeviceJaListBean.DeviceItemBean> data) {
        super(R.layout.item_facility_task_detail, data);
        this.mContext = context;
        this.mActivity = (HxFacilityTaskDetailActivity) context;
        this.mIsFinish = isFinish;
    }

    @Override
    protected void convert(final ViewHolder holder, HxFacilityTaskDetailBean.DataBean.DeviceJaListBean.DeviceItemBean deviceItemBean) {
        holder.mTvName.setText(deviceItemBean.getXunjianItemName());
        mImageAdapter = new HxTaskDetailImageAdapter();
        holder.mLsImg.setLayoutManager(
                new GridLayoutManager(mContext, 4));
        holder.mLsImg.setAdapter(mImageAdapter);
        holder.mLsImg.setNestedScrollingEnabled(false);
        switch (mIsFinish) {
            case 0: //未提交巡检单 可以修改
                holder.mGroup.setVisibility(View.VISIBLE);
                holder.mBtAddDes.setVisibility(View.VISIBLE);
                holder.mIvState.setVisibility(View.GONE);
                break;
            case 1: //已提交巡检单 不能修改
                holder.mGroup.setVisibility(View.GONE);
                holder.mBtAddDes.setVisibility(View.GONE);
                holder.mIvState.setVisibility(View.VISIBLE);
                break;
        }

        if (deviceItemBean.getImageName().size() <= 0) {
            //默认选择正常
            deviceItemBean.setCheckState(STATE_NORMAL);
            holder.mTvRemark.setVisibility(View.GONE);
        } else {
            holder.mTvRemark.setVisibility(View.VISIBLE);
            mImageAdapter.setDatas(deviceItemBean.getImageName(), mContext);
        }

        int checkState = deviceItemBean.getCheckState();
        setCheckedBox(holder, checkState, holder.mIvState);
        mActivity.loadText("检查结果：", holder.mTvRemark, deviceItemBean.getRemark(), "无描述");

        holder.mBtAddDes.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mDeviceItemBean = getData().get(holder.getLayoutPosition());

                mDialogFrament = HxSationDialogFragment.newInstance();
                mDialogFrament.show(mActivity.getFragmentManager(), "image");
                mDialogFrament.setLoadLisetener(new HxSationDialogFragment.UpLoadLisetener() {
                    @Override
                    public void upload() {
                        if (!TextUtils.isEmpty(mDialogFrament.getDes()) && mDialogFrament.getImgs().length != 0) {
                            ApiCommitAroundItem(holder.getLayoutPosition(), mDeviceItemBean.getIdNum(), mDeviceItemBean.getCheckState(), mDialogFrament
                                            .getDes(),
                                    mDialogFrament.getImgs());
                        } else {
                            ToastUtil.showToast("数据不能为空");
                        }
                    }
                });
            }
        });
        holder.mGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int checkedId) {
                mDeviceItemBean = getData().get(holder.getLayoutPosition());
                switch (checkedId) {
                    case R.id.normal:
                        mDeviceItemBean.setCheckState(STATE_NORMAL);
                        break;
                    case R.id.error:
                        mDeviceItemBean.setCheckState(STATE_ERROR);
                        break;
                    default:
                        break;
                }
            }
        });
    }

    /**
     * 设置
     *
     * @param viewHolder
     * @param checkstate
     * @param imageView
     */
    private void setCheckedBox(ViewHolder viewHolder, int checkstate, ImageView imageView) {
        switch (checkstate) {
            case 0:
            case 1:
                viewHolder.mNormal.setChecked(true);
                viewHolder.mError.setChecked(false);
                imageView.setImageResource(R.drawable.icon_state_normal);
                break;
            case 2:
                viewHolder.mNormal.setChecked(false);
                viewHolder.mError.setChecked(true);
                imageView.setImageResource(R.drawable.icon_state_error);
                break;
        }
    }

    /**
     * 提交巡检单
     *
     * @param id
     * @param state
     * @param des
     * @param imgs
     */
    private void ApiCommitAroundItem(final int position, int id, int state, String des, String[] imgs) {
        final ProgressDialog dialog = DialogUtil.getWaitDialog(mContext, "提交中...");
        dialog.show();
        Call<HxCommitTaskDetailBean> call = HxTransmitRequestHelper.getRequestApi().putCommitXunJianItem(id, state, des,
                RequestHelper.createFileParts(imgs));
        call.enqueue(new Callback<HxCommitTaskDetailBean>() {
            @Override
            public void onResponse(Call<HxCommitTaskDetailBean> call, Response<HxCommitTaskDetailBean> response) {
                dialog.dismiss();
                HxCommitTaskDetailBean taskDetailBean = response.body();
                if (taskDetailBean.isSuccessful()) {
                    if (!Util.checkNull(mDialogFrament)) {
                        mDialogFrament.dismiss();
                    }
                    updateData(taskDetailBean, position);
                } else {
                    ToastUtil.showToast(taskDetailBean.getMsg());
                }
            }

            @Override
            public void onFailure(Call<HxCommitTaskDetailBean> call, Throwable t) {
                ToastUtil.showToast("网络故障");
            }
        });
    }

    private void updateData(HxCommitTaskDetailBean aroundItem, int position) {
        getData().remove(position);
        HxFacilityTaskDetailBean.DataBean.DeviceJaListBean.DeviceItemBean deviceListBean = new HxFacilityTaskDetailBean.DataBean.DeviceJaListBean.DeviceItemBean();
        deviceListBean.setImageName(aroundItem.getImageName());
        deviceListBean.setCheckState(aroundItem.getCheckState());
        deviceListBean.setIsFinish(COMMIT_FINSIH);
        deviceListBean.setIdNum(aroundItem.getId());
        deviceListBean.setRemark(aroundItem.getDescription());
        deviceListBean.setXunjianItemName(aroundItem.getName());
        getData().add(position, deviceListBean);
        notifyDataSetChanged();
    }

    class ViewHolder extends BaseViewHolder {
        @BindView(R.id.tv_name)
        TextView     mTvName;
        @BindView(R.id.normal)
        RadioButton  mNormal;
        @BindView(R.id.error)
        RadioButton  mError;
        @BindView(R.id.group)
        RadioGroup   mGroup;
        @BindView(R.id.bt_add_des)
        ImageButton  mBtAddDes;
        @BindView(R.id.ll_radio)
        LinearLayout mLlRadio;
        @BindView(R.id.tv_remark)
        TextView     mTvRemark;
        @BindView(R.id.ls_img)
        RecyclerView mLsImg;
        @BindView(R.id.iv_state)
        ImageView    mIvState;

        public ViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }
}
